<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :permission="permissionList"
               :search.sync="search"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               :before-open="beforeOpen"
               :page="page"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.user_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="info"
                   size="small"
                   plain
                   v-if="userInfo.authority.includes('admin')"
                   icon="el-icon-user"
                   @click="handleGrant('1')">角色配置
        </el-button>
        <el-button type="info"
                   size="small"
                   plain
                   v-if="userInfo.authority.includes('admin')"
                   icon="el-icon-user"
                   @click="handleGrant('2')">所属分组
        </el-button>
        <el-button type="primary"
                   size="small"
                   plain
                   v-if="permission.user_reset"
                   icon="el-icon-refresh"
                   @click="handleReset">密码重置
        </el-button>
        <!--        <el-button type="success"-->
        <!--                   size="small"-->
        <!--                   plain-->
        <!--                   v-if="userInfo.authority.includes('admin')"-->
        <!--                   icon="el-icon-upload2"-->
        <!--                   @click="handleImport">导入-->
        <!--        </el-button>-->
        <!--        <el-button type="warning"-->
        <!--                   size="small"-->
        <!--                   plain-->
        <!--                   v-if="userInfo.authority.includes('admin')"-->
        <!--                   icon="el-icon-download"-->
        <!--                   @click="handleExport">导出-->
        <!--        </el-button>-->
      </template>
      <template slot-scope="{row}"
                slot="roleId">
        <el-tag>{{ row.roleName }}</el-tag>
      </template>
      <template slot-scope="{row}"
                slot="deptId">
        <el-tag>{{ row.deptName }}</el-tag>
      </template>
    </avue-crud>
    <el-dialog title="用户角色配置"
               append-to-body
               :visible.sync="roleBox"
               width="345px">

      <el-tree :data="roleGrantList"
               show-checkbox
               :default-expand-all="false"
               node-key="id"
               ref="treeRole"
               :default-checked-keys="roleTreeObj"
               :props="props">
      </el-tree>

      <span slot="footer" class="dialog-footer">
            <el-button @click="roleBox = false">取 消</el-button>
            <el-button type="primary"
                       @click="submitRole">确 定</el-button>
          </span>
    </el-dialog>
    <!-- 所属分组-->
    <el-dialog title="所属分组"
               append-to-body
               :visible.sync="userGroupBox"
               width="345px">

      <el-tree :data="userGroupData"
               show-checkbox
               :default-expand-all="false"
               node-key="id"
               ref="treeUserGroup"
               :default-checked-keys="userGroupTreeObj"
               :props="props">
      </el-tree>

      <span slot="footer" class="dialog-footer">
            <el-button @click="userGroupBox = false">取 消</el-button>
            <el-button type="primary"
                       @click="submitUserGroup">确 定</el-button>
          </span>
    </el-dialog>
    <el-dialog title="用户数据导入"
               append-to-body
               :visible.sync="excelBox"
               width="555px">
      <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate()">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  getUser,
  remove,
  update,
  add,
  grant,
  resetPassword,
  getRoleTree,
  getXsTree,
  getJsTree, getUserUserGroupList, grantUserUserGroup, getUserSomeUserGroup
} from "@/api/system/user";
import {mapGetters} from "vuex";
import website from '@/config/website';
import {getToken} from '@/util/auth';

export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      form: {},
      relateType: 2,
      search: {},
      roleBox: false,
      excelBox: false,
      userGroupBox: false,
      loading: true,
      selectionList: [],
      query: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      init: {
        roleTree: [],
        deptTree: [],
      },
      props: {
        label: "title",
        value: "key"
      },
      roleGrantList: [],
      roleTreeObj: [],
      userGroupData: [],
      userGroupTreeObj: [],
      option: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        selection: true,
        viewBtn: true,
        column: [
          {
            label: "登录账号",
            prop: "account",
            search: true,
            rules: [{
              required: true,
              message: "请输入登录账号",
              trigger: "blur"
            }],
            span: website.tenantMode ? 12 : 24,
          },
          {
            label: "所属租户",
            prop: "tenantId",
            type: "tree",
            dicUrl: "/api/ManageUser/GetSelectTenantList",
            props: {
              label: "tenantName",
              value: "tenantId"
            },
            cascader: ['groupIds'],
            hide: !website.tenantMode,
            addDisplay: website.tenantMode,
            editDisplay: website.tenantMode,
            viewDisplay: website.tenantMode,
            search: true,
            rules: [{
              required: true,
              message: "请选择所属租户",
              trigger: "click"
            }]
          },
          {
            label: '密码',
            prop: 'password',
            hide: true,
            editDisplay: false,
            viewDisplay: false,
            rules: [{required: true, validator: validatePass, trigger: 'blur'}]
          },
          {
            label: '确认密码',
            prop: 'password2',
            hide: true,
            editDisplay: false,
            viewDisplay: false,
            rules: [{required: true, validator: validatePass2, trigger: 'blur'}]
          },
          {
            label: "用户昵称",
            prop: "name",
            rules: [{
              required: true,
              message: "请输入用户昵称",
              trigger: "blur"
            }]
          },
          // {
          //   label: "用户姓名",
          //   prop: "realName",
          //   search: true,
          //   rules: [{
          //     required: true,
          //     message: "请输入用户姓名",
          //     trigger: "blur"
          //   }]
          // },
          {
            label: "所属角色",
            prop: "roleId",
            multiple: true,
            type: "tree",
            dicData: [],
            props: {
              label: "title"
            },
            slot: true,
            // checkStrictly: true,
            // rules: [{
            //   // required: true,
            //   message: "请选择所属角色",
            //   trigger: "click"
            // }],
            hide: true,
          },
          // {
          //   label: "所属分组",
          //   prop: "groupId",
          //   multiple: true,
          //   type: "tree",
          //   props: {
          //     label: "title"
          //   },
          //   slot: true,
          //   checkStrictly: true,
          //   rules: [{
          //     required: true,
          //     message: "请选择所属分组",
          //     trigger: "click"
          //   }],
          //   dicUrl: "/api/ManageUser/GetUserUserGroupList?tenantId={{key}}",
          //   hide: true,
          // },
          {
            label: "关联类型",
            prop: "relateType",
            type: "select",
            search: true,
            cascader: ['relateId'],
            rules: [{
              required: false,
              message: "请选择关联类型",
              trigger: "click"
            }],
            // cascader: ['relateId'],
            dicData: [
              // {
              //   label: "学生",
              //   value: 1
              // },
              {
                label: "教师（校长）",
                value: 2
              },
              {
                label: "家长",
                value: 3
              },
              // {
              //   label: "学校其他工作人员",
              //   value: 4
              // }
            ],
            value: 2,
            dataType: 'number',
            hide: false,
            change: ({value}) => {
              this.relateTypeChange(value);
            }
          },
          {
            label: '关联用户',
            prop: 'relateName',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            // rules: [{required: true, validator: validatePass2, trigger: 'blur'}]
          },
          {
            label: "关联用户",
            prop: "relateId",
            type: "tree",
            search: false,
            hide: true,
            dicData: [],
            props: {
              label: "title"
            },
            slot: true,
            checkStrictly: true,
            rules: [{
              required: false,
              message: "请选择关联用户",
              trigger: "click"
            }]
          },
          // {
          //   label: "所属部门",
          //   prop: "deptId",
          //   type: "tree",
          //   search:true,
          //   multiple: true,
          //   dicData: [],
          //   props: {
          //     label: "title"
          //   },
          //   slot: true,
          //   checkStrictly: true,
          //   rules: [{
          //     required: true,
          //     message: "请选择所属部门",
          //     trigger: "click"
          //   }]
          // },
          // {
          //   label: "用户编号",
          //   prop: "code",
          //   hide: true,
          // },
          // {
          //   label: "所属岗位",
          //   prop: "postId",
          //   type: "tree",
          //   multiple: true,
          //   dicData: [],
          //   hide: true,
          //   props: {
          //     label: "postName",
          //     value: "id"
          //   },
          //   rules: [{
          //     required: false,
          //     message: "请选择所属岗位",
          //     trigger: "click"
          //   }],
          // },
          // {
          //   label: "手机号码",
          //   prop: "phone",
          //   overHidden: true,
          //   rules: [{
          //     required: true,
          //     message: "请输入手机号",
          //     trigger: "click"
          //   }],
          //   maxlength: 11,
          //   showWordLimit: true,
          // },
          // {
          //   label: "电子邮箱",
          //   prop: "email",
          //   hide: true,
          //   overHidden: true
          // },
          // {
          //   label: "用户性别",
          //   prop: "sex",
          //   type: "select",
          //   dicData: [
          //     {
          //       label: "男",
          //       value: 1
          //     },
          //     {
          //       label: "女",
          //       value: 2
          //     },
          //     {
          //       label: "未知",
          //       value: 3
          //     }
          //   ],
          //   hide: true
          // },
          // {
          //   label: "用户生日",
          //   type: "date",
          //   prop: "birthday",
          //   format: "yyyy-MM-dd hh:mm:ss",
          //   valueFormat: "yyyy-MM-dd hh:mm:ss",
          //   hide: true
          // },
          {
            label: "账号状态",
            prop: "statusName",
            hide: true,
            display: false
          },
          {
            label: "PC端登陆",
            prop: "isPcLogin",
            type: "select",
            dicData: [
              {
                label: "是",
                value: 1
              },
              {
                label: "否",
                value: 0
              }
            ],
            hide: false
          },
        ]
      },
      data: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '模板上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '模板上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: "/api/blade-user/import-user"
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          }
        ]
      }
    };
  },
  watch: {
    'form.tenantId'() {
      if (this.form.tenantId !== '') {
        // getDeptTree(this.form.tenantId).then(res => {
        //   const column = this.findObject(this.option.column, "deptId");
        //   column.dicData = res.data.data;
        // });
        getRoleTree(this.form.tenantId).then(res => {
          const column = this.findObject(this.option.column, "roleId");
          column.dicData = res.data.data;
        });
        // getPostList(this.form.tenantId).then(res => {
        //   const column = this.findObject(this.option.column, "postId");
        //   column.dicData = res.data.data;
        // });
        if (this.relateType == 2) {
          getJsTree(this.form.tenantId).then(res => {
            const column = this.findObject(this.option.column, "relateId");
            column.dicData = res.data.data;
          });
        }
        if (this.relateType == 3) {
          getXsTree(this.form.tenantId).then(res => {
            const column = this.findObject(this.option.column, "relateId");
            let data = res.data.data
            // let list = []
            // data.forEach(item => {
            //   let arr = {}
            //   arr.value = item.id
            //   arr.title = item.jzName
            //   list.push(arr)
            // })
            column.dicData = data;
          });
        }

        // getBjTree(this.form.tenantId).then(res => {
        //   const column = this.findObject(this.option.column, "bjId");
        //   column.dicData = res.data.data;
        // });
      }
    },
  },
  computed: {
    ...mapGetters(["userInfo", "permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.user_add, false),
        viewBtn: this.vaildData(this.permission.user_view, false),
        delBtn: this.vaildData(this.permission.user_delete, false),
        editBtn: this.vaildData(this.permission.user_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  methods: {
    relateTypeChange(v) {
      this.relateType = v;
      // if(this.relateType == 1 ){
      //   getXsTree(this.form.tenantId).then(res => {
      //     const column = this.findObject(this.option.column, "relateId");
      //     column.dicData = res.data.data;
      //   });
      // }
      if (this.form.tenantId === '') return 0
      if (this.relateType == 2) {

        getJsTree(this.form.tenantId).then(res => {
          const column = this.findObject(this.option.column, "relateId");
          column.dicData = res.data.data;
        });
      }
      if (this.relateType == 3) {
        getXsTree(this.form.tenantId).then(res => {
          const column = this.findObject(this.option.column, "relateId");
          let data = res.data.data
          // let list = []
          // listdata.forEach(item => {
          //   let arr = {}
          //   arr.value = item.id
          //   arr.title = item.jzName
          //   list.push(arr)
          // })
          column.dicData = data;
        });
        // jzgetList(1,500,{}).then(res => {
        //   const column = this.findObject(this.option.column, "relateId");
        //   let data = res.data.data.records
        //   let list = []
        //   data.forEach(item=>{
        //     let arr = {}
        //     arr.value = item.id
        //     arr.title = item.jzName
        //     list.push(arr)
        //   })
        //   column.dicData = list;
        // });
      }
    },
    //角色配置弹窗确定
    submitRole() {
      const roleList = this.$refs.treeRole.getCheckedKeys().join(",");
      let params = {
        userIds: this.ids,
        roleIds: roleList
      }
      grant(params).then(() => {
        this.roleBox = false;
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.onLoad(this.page);
      });
    },
    //所属分组弹窗确实
    submitUserGroup() {
      const userGroup = this.$refs.treeUserGroup.getCheckedKeys().join(",");
      let params = {
        userIds: this.ids,
        groupIds: userGroup
      }
      grantUserUserGroup(params).then(() => {
        this.userGroupBox = false;
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.onLoad(this.page);
      });
    },
    rowSave(row, done, loading) {
      console.log()
      // row.deptId = '0',//row.deptId.join(",");
      row.roleId = row.roleId.join(",");
      // row.groupId = row.groupId.join(",");
      // row.postId = row.postId.join(",");
      // if (!isMobile(row.phone)) {
      //   this.$message({
      //     type: "warning",
      //     message: "请输入正确手机号!"
      //   });
      //   loading();
      //   return 0
      // }
      add({
        ...row,
        relateId: row.relateId ? row.relateId : 0,
        isPcLogin: row.isPcLogin ? row.isPcLogin : 1,
      }).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      console.log('编辑',row)
      row.deptId = row.deptId.join(",");
      row.roleId = row.roleId.join(",");
      // row.groupId = row.groupId.join(",");
      // row.postId = row.postId.join(",");
      // if (!isMobile(row.phone)) {
      //   this.$message({
      //     type: "warning",
      //     message: "请输入正确手机号!"
      //   });
      //   loading();
      //   return 0
      // }
      update({
        ...row,
        relateId: row.relateId ? row.relateId : 0,
        isPcLogin: row.isPcLogin ? row.isPcLogin : 1,
      }).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let params = {
            ids: row.id
          }
          return remove(params);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let params = {
            ids: this.ids
          }
          return remove(params);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleReset() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择账号密码重置为123456?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return resetPassword({userIds: this.ids});
        })
        .then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleGrant(type) {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择数据");
        return;
      } else if (this.selectionList.length > 1) {
        this.$message.warning("仅可选择一条数据");
        return;
      }
      if (type === '1') {
        this.roleTreeObj = [];
        if (this.selectionList.length === 1) {
          this.roleTreeObj = this.selectionList[0].roleId.split(",");
        }
        getRoleTree().then(res => {
          this.roleGrantList = res.data.data;
          this.roleBox = true;
        });
      } else if (type === '2') {
        this.userGroupTreeObj = [];
        console.log('this.selectionList', this.selectionList)
        // if (this.selectionList.length === 1 && this.selectionList[0].relateId !== null) {
        //   this.userGroupTreeObj = this.selectionList[0].groupId.split(",");
        // }
        getUserUserGroupList().then(res => {
          this.userGroupData = res.data.data;
          getUserSomeUserGroup({AppUserId: this.selectionList[0].relateId}).then(resData => {
            this.userGroupTreeObj = resData.data.data
            this.userGroupBox = true;
          })
        });
      }

    },

    handleImport() {
      this.excelBox = true;
    },
    uploadAfter(res, done, loading, column) {
      window.console.log(column);
      done();
      this.excelBox = false;
      this.refreshChange();
    },
    handleExport() {
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        console.log(getToken(), this.search.account, this.search.realName)
        window.open(`/api/ManageUser/ExportUserList?AccessToken=${getToken()}&account=${this.search.account}`);
      });
    },
    handleTemplate() {
      window.open(`/api/blade-user/export-template?blade-auth=${getToken()}`);
    },
    beforeOpen(done, type) {
      console.log(type)
      if (["edit", "view"].includes(type)) {
        getUser(this.form.id).then(res => {
          this.form = res.data.data;
          if (this.form.hasOwnProperty("deptId")) {
            this.form.deptId = this.form.deptId.split(",");
          }
          if (this.form.hasOwnProperty("roleId")) {
            this.form.roleId = this.form.roleId.split(",");
          }
        });
      }
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
      // getDeptTree(this.form.tenantId).then(res => {
      //   const column = this.findObject(this.option.column, "deptId");
      //   column.dicData = res.data.data;
      // });
      getRoleTree(this.form.tenantId).then(res => {
        const column = this.findObject(this.option.column, "roleId");
        column.dicData = res.data.data;
      });
      // getPostList(this.form.tenantId).then(res => {
      //   const column = this.findObject(this.option.column, "postId");
      //   column.dicData = res.data.data;
      // });
      if (this.relateType == 2) {
        getJsTree(this.form.tenantId).then(res => {
          const column = this.findObject(this.option.column, "relateId");
          column.dicData = res.data.data;
        });
      }
      if (this.relateType == 3) {
        getXsTree(this.form.tenantId).then(res => {
          const column = this.findObject(this.option.column, "relateId");
          let data = res.data.data
          // let list = []
          // data.forEach(item => {
          //   let arr = {}
          //   arr.value = item.id
          //   arr.title = item.jzName
          //   list.push(arr)
          // })
          column.dicData = data;
        });
      }
    }
  }
};
</script>

<style>
</style>
